﻿using System;
using System.IO;
using System.Net.Sockets;
using System.Text;

namespace HTTP
{
    class Sockets
    {
        private Socket socket;
        private string adresse;
        private int port;
        private int timeout { get; set; }

         public Sockets(string adresse, int port)
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            this.adresse = adresse;
            this.port = port;
            Open(adresse, port);
            timeout = 5;
        }

        public bool isConnected()
        {
            return socket.Connected;
        }

        public void Open(string url, int port)
        {
            socket = ConnectSocket(url, port);
        }

        public void Close()
        {
            socket.Close();
        }

        public void Send(string command)
        {
            byte[] msg = Encoding.ASCII.GetBytes(command);
            socket.Send(msg);
        }

        public String Receive()
        {
            byte[] retMsg = new byte[1024];
            socket.Receive(retMsg);
            string str = Encoding.ASCII.GetString(retMsg);
            return str;
        }

        public Stream GetStream()
        {
            NetworkStream ns = new NetworkStream(socket);
            return ns;
        }

        public String ConnectionTest(string url, int port)
        {
            Send("GET / HTTP/1.1\r\nHost: " + url + "\r\nConnection: Close\r\n\r\n");
            return Receive();
        }

        private Socket ConnectSocket(string server, int port)
        {
            socket.Connect(server, port);
            return socket;
        }
    }
}
